import { getAddressListApi } from '@/api/address'
import { Address } from '@/types/model'
import { defineComponent, reactive } from 'vue'
import { useRouter } from 'vue-router'

interface AddressData {
  list: Address[]
}

/* 地址列表 */
const useAddressListEffect = () => {
  const data: AddressData = reactive({
    list: []
  })

  const getAddressList = async () => {
    const res = await getAddressListApi()
    if (res.code === 0) {
      data.list = res.data
    }
  }

  getAddressList()

  return {
    data
  }
}

export default defineComponent({
  name: 'AddressManage',
  setup () {
    const router = useRouter()
    const { data } = useAddressListEffect()

    /* render 函数 */
    return () => {
      const addressList = data.list.map(address => (
        <div class="address">
          <div class="address__content">
            <div class="address__content__header">
              <div class="address__content__name">{ address.name }</div>
              <div class="address__content__phone">{ address.phone }</div>
            </div>
            <div class="address__content__detail">{ `${address.city} ${address.area} ${address.number}` }</div>
          </div>
          <div class="iconfont icon-back" onClick={ () => { router.push(`/editAddress/${address.id}`) } }></div>
        </div>
      ))
      return (
        <div class="address__manage">
          <header>
            <div class="iconfont icon-back" onClick={ () => { router.replace({ name: 'PersonCenter' }) }}></div>
            <div class="title">管理收货地址</div>
            <div class="new" onClick={ () => { router.push('/editAddress/0') } }>新建</div>
          </header>
          <div class="address__title">我的收货地址</div>
          <div class="addresses">{ addressList }</div>
        </div>
      )
    }
  }
})
